﻿using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;

namespace CodeContrib.Web
{
	// http://haacked.com/archive/2005/04/29/using-embedded-resources-for-client-scripts.aspx
	public class ScriptHelper : IScriptHelper
	{
		private static string UnpackEmbeddedResourceToString(string resourceName)
		{
			var executingAssembly = Assembly.GetExecutingAssembly();

			var resourceStream = executingAssembly.GetManifestResourceStream(typeof (ScriptHelper), resourceName);

			if (resourceStream == null)
			{
				return string.Empty;
			}

			using (var reader = new StreamReader(resourceStream, Encoding.ASCII))
			{
				return reader.ReadToEnd();
			}
		}

		public string UnpackScript(string resourceName, string mimeType)
		{
			var language = "javascript";
			var extension = Path.GetExtension(resourceName);

			if (string.Compare(extension, ".vbs", true, CultureInfo.InvariantCulture) == 0)
			{
				language = "vbscript";
			}

			return UnpackScript(resourceName, mimeType, language);
		}

		public string UnpackScript(string resourceName, string mimeType, string scriptLanguage)
		{
			var script = new StringBuilder();

			script.AppendLine("<script language=\"{0}\" type=\"{1}\">", scriptLanguage, mimeType);
			script.AppendLine(UnpackEmbeddedResourceToString("Resources.Scripts." + resourceName));
			script.AppendLine("</script>");

			return script.ToString();
		}
	}
}